package com.photovoltaic.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.photovoltaic.auth.entity.Permission;
import com.photovoltaic.auth.entity.Role;
import com.photovoltaic.auth.security.services.UserDetailsImpl;
import com.photovoltaic.auth.service.OperationLogService;
import com.photovoltaic.auth.service.RoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/auth/roles")
@RequiredArgsConstructor
public class RoleController {
    
    private final RoleService roleService;
    private final OperationLogService operationLogService;
    
    @GetMapping
    @PreAuthorize("hasAuthority('role:list')")
    public ResponseEntity<Page<Role>> getRoles(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String roleName) {
        
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        if (roleName != null && !roleName.isEmpty()) {
            queryWrapper.like(Role::getName, roleName);
        }
        
        Page<Role> page = roleService.page(new Page<>(current, size), queryWrapper);
        return ResponseEntity.ok(page);
    }
    
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('role:view')")
    public ResponseEntity<Role> getRoleById(@PathVariable Long id) {
        Role role = roleService.getById(id);
        if (role == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(role);
    }
    
    @GetMapping("/{id}/permissions")
    @PreAuthorize("hasAuthority('role:view')")
    public ResponseEntity<List<Permission>> getRolePermissions(@PathVariable Long id) {
        List<Permission> permissions = roleService.getRolePermissions(id);
        return ResponseEntity.ok(permissions);
    }
    
    @PostMapping
    @PreAuthorize("hasAuthority('role:add')")
    public ResponseEntity<Role> createRole(
            @RequestBody Role role,
            HttpServletRequest request,
            @AuthenticationPrincipal UserDetailsImpl currentUser) {
        
        boolean success = roleService.save(role);
        
        // 记录操作日志
        operationLogService.recordLog(
                currentUser.getId(),
                "ROLE_CREATE",
                "创建角色: " + role.getName(),
                request.getRemoteAddr(),
                success ? 1 : 0
        );
        
        return ResponseEntity.ok(role);
    }
    
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('role:edit')")
    public ResponseEntity<Role> updateRole(
            @PathVariable Long id,
            @RequestBody Role role,
            HttpServletRequest request,
            @AuthenticationPrincipal UserDetailsImpl currentUser) {
        
        role.setId(id);
        boolean success = roleService.updateById(role);
        
        // 记录操作日志
        operationLogService.recordLog(
                currentUser.getId(),
                "ROLE_UPDATE",
                "更新角色: " + role.getName(),
                request.getRemoteAddr(),
                success ? 1 : 0
        );
        
        return ResponseEntity.ok(role);
    }
    
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('role:delete')")
    public ResponseEntity<Map<String, Object>> deleteRole(
            @PathVariable Long id,
            HttpServletRequest request,
            @AuthenticationPrincipal UserDetailsImpl currentUser) {
        
        boolean success = roleService.removeById(id);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        
        // 记录操作日志
        operationLogService.recordLog(
                currentUser.getId(),
                "ROLE_DELETE",
                "删除角色: ID=" + id,
                request.getRemoteAddr(),
                success ? 1 : 0
        );
        
        return ResponseEntity.ok(result);
    }
    
    @PostMapping("/{roleId}/permissions/{permissionId}")
    @PreAuthorize("hasAuthority('role:edit')")
    public ResponseEntity<Map<String, Object>> assignPermission(
            @PathVariable Long roleId,
            @PathVariable Long permissionId,
            HttpServletRequest request,
            @AuthenticationPrincipal UserDetailsImpl currentUser) {
        
        boolean success = roleService.assignPermission(roleId, permissionId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        
        // 记录操作日志
        operationLogService.recordLog(
                currentUser.getId(),
                "ROLE_PERMISSION_ASSIGN",
                "为角色分配权限: 角色ID=" + roleId + ", 权限ID=" + permissionId,
                request.getRemoteAddr(),
                success ? 1 : 0
        );
        
        return ResponseEntity.ok(result);
    }
    
    @DeleteMapping("/{roleId}/permissions/{permissionId}")
    @PreAuthorize("hasAuthority('role:edit')")
    public ResponseEntity<Map<String, Object>> removePermission(
            @PathVariable Long roleId,
            @PathVariable Long permissionId,
            HttpServletRequest request,
            @AuthenticationPrincipal UserDetailsImpl currentUser) {
        
        boolean success = roleService.removePermission(roleId, permissionId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        
        // 记录操作日志
        operationLogService.recordLog(
                currentUser.getId(),
                "ROLE_PERMISSION_REMOVE",
                "移除角色权限: 角色ID=" + roleId + ", 权限ID=" + permissionId,
                request.getRemoteAddr(),
                success ? 1 : 0
        );
        
        return ResponseEntity.ok(result);
    }
} 